<template>
  <div class="material-receipt-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>收料维护</span>
          <el-button type="primary" @click="handleCreate">新建收料单</el-button>
        </div>
      </template>

      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="收料单号">
          <el-input
            v-model="queryForm.receiptNo"
            placeholder="请输入收料单号"
          />
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="queryForm.supplier" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="收料日期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态">
            <el-option label="待收料" value="pending" />
            <el-option label="部分收料" value="partial" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="receiptNo" label="收料单号" width="180" />
        <el-table-column prop="supplier" label="供应商" />
        <el-table-column prop="receiptDate" label="收料日期" width="180" />
        <el-table-column prop="totalQuantity" label="总数量" width="100" />
        <el-table-column prop="receivedQuantity" label="已收数量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="120" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button
              link
              type="primary"
              @click="handleReceive(scope.row)"
              v-if="['pending', 'partial'].includes(scope.row.status)"
              >收料</el-button
            >
            <el-button
              link
              type="danger"
              @click="handleCancel(scope.row)"
              v-if="scope.row.status === 'pending'"
              >取消</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑收料单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建收料单' : '收料单详情'"
      width="80%"
    >
      <el-form
        :model="receiptForm"
        label-width="100px"
        :rules="rules"
        ref="receiptFormRef"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplier">
              <el-select
                v-model="receiptForm.supplier"
                filterable
                remote
                placeholder="请选择供应商"
                :disabled="dialogType === 'view'"
              >
                <el-option
                  v-for="item in supplierOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收料日期" prop="receiptDate">
              <el-date-picker
                v-model="receiptForm.receiptDate"
                type="date"
                placeholder="选择日期"
                :disabled="dialogType === 'view'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouse">
              <el-select
                v-model="receiptForm.warehouse"
                placeholder="请选择仓库"
                :disabled="dialogType === 'view'"
              >
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-table
          :data="receiptForm.items"
          border
          style="width: 100%; margin-bottom: 20px"
        >
          <el-table-column type="index" width="50" label="序号" />
          <el-table-column prop="materialCode" label="物料编码" width="150">
            <template #default="scope">
              <el-input
                v-if="dialogType !== 'view'"
                v-model="scope.row.materialCode"
                placeholder="请输入物料编码"
              />
              <span v-else>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="materialName" label="物料名称" width="200" />
          <el-table-column prop="unit" label="单位" width="100" />
          <el-table-column prop="planQuantity" label="计划数量" width="120">
            <template #default="scope">
              <el-input-number
                v-if="dialogType !== 'view'"
                v-model="scope.row.planQuantity"
                :min="0"
                :precision="2"
              />
              <span v-else>{{ scope.row.planQuantity }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="receivedQuantity"
            label="已收数量"
            width="120"
          />
          <el-table-column prop="remark" label="备注">
            <template #default="scope">
              <el-input
                v-if="dialogType !== 'view'"
                v-model="scope.row.remark"
                placeholder="请输入备注"
              />
              <span v-else>{{ scope.row.remark }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="150"
            v-if="dialogType !== 'view'"
          >
            <template #default="scope">
              <el-button
                link
                type="danger"
                @click="handleRemoveItem(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="table-operations" v-if="dialogType !== 'view'">
          <el-button type="primary" @click="handleAddItem">添加物料</el-button>
        </div>

        <el-form-item label="备注">
          <el-input
            v-model="receiptForm.remark"
            type="textarea"
            :disabled="dialogType === 'view'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            v-if="dialogType !== 'view'"
          >
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 收料操作对话框 -->
    <el-dialog v-model="receiveDialogVisible" title="收料操作" width="60%">
      <el-form :model="receiveForm" label-width="100px">
        <el-table :data="receiveForm.items" border style="width: 100%">
          <el-table-column type="index" width="50" label="序号" />
          <el-table-column prop="materialCode" label="物料编码" width="150" />
          <el-table-column prop="materialName" label="物料名称" width="200" />
          <el-table-column prop="planQuantity" label="计划数量" width="120" />
          <el-table-column
            prop="receivedQuantity"
            label="已收数量"
            width="120"
          />
          <el-table-column prop="currentQuantity" label="本次收料" width="150">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.currentQuantity"
                :min="0"
                :max="scope.row.planQuantity - scope.row.receivedQuantity"
                :precision="2"
              />
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="receiveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleReceiveSubmit"
            >确认收料</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 查询表单
const queryForm = reactive({
  receiptNo: "",
  supplier: "",
  dateRange: [],
  status: "",
});

// 表格数据
const tableData = ref([
  {
    receiptNo: "REC202403200001",
    supplier: "供应商A",
    receiptDate: "2024-03-20",
    totalQuantity: 100,
    receivedQuantity: 0,
    status: "pending",
    creator: "张三",
  },
]);

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 对话框控制
const dialogVisible = ref(false);
const dialogType = ref("create");
const receiveDialogVisible = ref(false);

// 表单数据
const receiptForm = reactive({
  supplier: "",
  receiptDate: "",
  warehouse: "",
  items: [],
  remark: "",
});

const receiveForm = reactive({
  items: [],
});

// 选项数据
const supplierOptions = ref([
  { value: "supplier1", label: "供应商A" },
  { value: "supplier2", label: "供应商B" },
]);

const warehouseOptions = ref([
  { value: "wh1", label: "仓库A" },
  { value: "wh2", label: "仓库B" },
]);

// 表单校验规则
const rules = {
  supplier: [{ required: true, message: "请选择供应商", trigger: "change" }],
  receiptDate: [
    { required: true, message: "请选择收料日期", trigger: "change" },
  ],
  warehouse: [{ required: true, message: "请选择仓库", trigger: "change" }],
};

// 状态处理方法
const getStatusType = (status) => {
  const statusMap = {
    pending: "warning",
    partial: "primary",
    completed: "success",
    cancelled: "info",
  };
  return statusMap[status];
};

const getStatusText = (status) => {
  const statusMap = {
    pending: "待收料",
    partial: "部分收料",
    completed: "已完成",
    cancelled: "已取消",
  };
  return statusMap[status];
};

// 查询方法
const handleSearch = () => {
  // 实现查询逻辑
};

const handleReset = () => {
  queryForm.receiptNo = "";
  queryForm.supplier = "";
  queryForm.dateRange = [];
  queryForm.status = "";
};

// 表单操作方法
const handleCreate = () => {
  dialogType.value = "create";
  dialogVisible.value = true;
  Object.assign(receiptForm, {
    supplier: "",
    receiptDate: "",
    warehouse: "",
    items: [],
    remark: "",
  });
};

const handleView = (row) => {
  dialogType.value = "view";
  dialogVisible.value = true;
  // 加载收料单详情
};

const handleReceive = (row) => {
  receiveDialogVisible.value = true;
  // 加载待收料明细
  receiveForm.items = [
    {
      materialCode: "M001",
      materialName: "物料A",
      planQuantity: 100,
      receivedQuantity: 0,
      currentQuantity: 0,
      remark: "",
    },
  ];
};

const handleCancel = (row) => {
  ElMessageBox.confirm("确认取消该收料单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    ElMessage.success("取消成功");
  });
};

// 物料明细操作
const handleAddItem = () => {
  receiptForm.items.push({
    materialCode: "",
    materialName: "",
    unit: "",
    planQuantity: 0,
    receivedQuantity: 0,
    remark: "",
  });
};

const handleRemoveItem = (index) => {
  receiptForm.items.splice(index, 1);
};

// 表单提交
const handleSubmit = () => {
  // 实现保存逻辑
  ElMessage.success("保存成功");
  dialogVisible.value = false;
};

const handleReceiveSubmit = () => {
  // 实现收料逻辑
  ElMessage.success("收料成功");
  receiveDialogVisible.value = false;
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  // 重新加载数据
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  // 重新加载数据
};
</script>

<style scoped>
.material-receipt-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
